import logo from "./logo.svg";
import "./App.css";
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { fetchCar } from "./store";

function App() {
  const car = useSelector((state) => state.car);
  console.log(car)
  const allPrice = car.filter(v => v.check).reduce((p, n) => p + n.price * n.count , 0)
  const allCount = car.reduce((p, n) => p + n.count , 0)
  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(fetchCar());
  }, []);
  return (
    <div className="App">
      <table>
        <tr>
          <td>状态</td>
          <td>图片</td>
          <td>标题</td>
          <td>描述</td>
          <td>数量</td>
          <td>价格</td>
          <td>库存</td>
          <td>操作</td>
        </tr>
        {car.length === 0
          ? "购物车暂无数据"
          : car.map((v, i) => {
              return (
                <tr key={i}>
                  <td>
                    <input
                      type="checkbox"
                      checked={v.check}
                      onChange={() =>
                        dispatch({ type: "switchItem", payload: v })
                      }
                    />
                  </td>
                  <td>
                    <img src={v.image} alt="" />
                  </td>
                  <td>{v.title}</td>
                  <td>{v.desc}</td>
                  <td>
                    <button
                      onClick={() => dispatch({ type: "subItem", payload: v })}
                    >
                      -
                    </button>
                    <span>{v.count}</span>
                    <button
                      onClick={() => {
                        if (v.count >= v.max) {
                          alert("库存不足");
                        } else {
                          dispatch({ type: "addItem", payload: v });
                        }
                      }}
                    >
                      +
                    </button>
                  </td>
                  <td>{v.price}</td>
                  <td>{v.max}</td>
                  <td>
                    
                    <button onClick={() => dispatch({ type: 'removeItem', payload: v })}>删除</button></td>
                </tr>
              );
            })}
      </table>
      <h2>
        <input type="checkbox" /> 全选
        <span>总价：{ allPrice.toFixed(2) }</span>
        <span>总数量：{allCount}</span>
      </h2>
    </div>
  );
}

export default App;
